package ejemplo.transformacion.xsl.servlets;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.SAXException;

import com.thoughtworks.xstream.XStream;

import ejemplo.transformacion.xsl.model.GrupoTareas;


public class GruposTareasControlador extends HttpServlet {
	private static final long serialVersionUID = 1L;
       Log log=LogFactory.getLog(this.getClass());
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String vistaXSL = "grupoTareaSimple.xsl";
		String modeloXML ;
		
		GrupoTareas grupoTareas=new GrupoTareas(1, "supergrupo");
		XStream xstream = new XStream();  


		
		
		xstream.autodetectAnnotations(true);
		 modeloXML = xstream.toXML(grupoTareas);
		

		log.info(modeloXML);
		


		String transformacion;
		try {
			transformacion = transforma(modeloXML, vistaXSL);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServletException(e);
		}
		

	        response.getWriter().print(transformacion);
		
		
	        response.getWriter().close();
	
	}

	
	


	private String transforma(String modeloXML, String vistaXSL)
			throws TransformerFactoryConfigurationError,
			TransformerConfigurationException, TransformerException {
		Source xmlSource = dameSource(modeloXML);
		Source xsltSource = new StreamSource(new File(getServletContext().getRealPath(vistaXSL)));
		
		StringWriter cadenaSalida = new StringWriter();
		
		Result bufferResultado = new StreamResult(cadenaSalida);
		
		TransformerFactory factoriaTrans = TransformerFactory.newInstance();
		Transformer transformador = factoriaTrans.newTransformer(xsltSource);
		
		transformador.transform(xmlSource, bufferResultado);
		
		String transformacion = cadenaSalida.toString();
		return transformacion;
	}




	private Source dameSource(String modeloXML) {
		StringReader reader = new StringReader(modeloXML);
		Source xmlSource = new StreamSource(reader);
		return xmlSource;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}
